const InboundDocument = require('../models/InboundDocument');
const Goods = require('../models/Goods');

class InboundController {
  // 获取所有入库单据
  static getAllInboundDocuments(req, res) {
    InboundDocument.findAll((err, documents) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '获取入库单据列表失败',
          error: err.message
        });
      }
      
      res.json({
        success: true,
        data: documents
      });
    });
  }

  // 根据ID获取入库单据
  static getInboundDocumentById(req, res) {
    const { id } = req.params;
    
    InboundDocument.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询入库单据失败',
          error: err.message
        });
      }
      
      if (!document) {
        return res.status(404).json({
          success: false,
          message: '入库单据未找到'
        });
      }
      
      res.json({
        success: true,
        data: document
      });
    });
  }

  // 创建新入库单据
  static createInboundDocument(req, res) {
    const { goodsId, supplier, quantity, expectedArrivalDate, operator, notes } = req.body;
    
    // 验证必填字段
    if (!goodsId || !supplier) {
      return res.status(400).json({
        success: false,
        message: '货物ID和供应商为必填项'
      });
    }
    
    const newDocument = new InboundDocument(
      null,
      goodsId,
      supplier,
      quantity || 0,
      expectedArrivalDate || new Date(),
      null,
      'pending',
      operator || '',
      notes || '',
      new Date()
    );
    
    // 验证货物是否存在
    Goods.findById(goodsId, (err, goods) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '验证货物失败',
          error: err.message
        });
      }
      
      if (!goods) {
        return res.status(400).json({
          success: false,
          message: '指定的货物不存在'
        });
      }
      
      // 保存入库单据
      newDocument.save((err, result) => {
        if (err) {
          return res.status(500).json({
            success: false,
            message: '创建入库单据失败',
            error: err.message
          });
        }
        
        res.status(201).json({
          success: true,
          message: '入库单据创建成功',
          data: { id: result.id, ...newDocument }
        });
      });
    });
  }

  // 更新入库单据状态
  static updateInboundDocumentStatus(req, res) {
    const { id } = req.params;
    const { status, actualQuantity, arrivalDate } = req.body;
    
    InboundDocument.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询入库单据失败',
          error: err.message
        });
      }
      
      if (!document) {
        return res.status(404).json({
          success: false,
          message: '入库单据未找到'
        });
      }
      
      // 创建入库单据对象
      const docObj = new InboundDocument(
        document.id,
        document.goods_id,
        document.supplier,
        document.quantity,
        document.expected_arrival_date,
        document.actual_arrival_date,
        document.status,
        document.operator,
        document.notes,
        document.created_at
      );
      
      if (status === 'completed') {
        docObj.complete(actualQuantity || document.quantity, arrivalDate || new Date(), (err, result) => {
          if (err) {
            return res.status(500).json({
              success: false,
              message: '完成入库操作失败',
              error: err.message
            });
          }
          
          // 更新货物库存
          Goods.findById(document.goods_id, (err, goods) => {
            if (err) {
              return res.status(500).json({
                success: false,
                message: '查询货物失败',
                error: err.message
              });
            }
            
            if (!goods) {
              return res.status(400).json({
                success: false,
                message: '关联的货物不存在'
              });
            }
            
            const goodsObj = new Goods(
              goods.id,
              goods.name,
              goods.sku,
              goods.quantity,
              goods.location,
              goods.status,
              goods.batch_number,
              goods.expiry_date,
              goods.created_at
            );
            
            goodsObj.checkin(actualQuantity || document.quantity, (err, result) => {
              if (err) {
                return res.status(500).json({
                  success: false,
                  message: '更新货物库存失败',
                  error: err.message
                });
              }
              
              res.json({
                success: true,
                message: '入库单据状态更新成功，货物库存已更新',
                data: docObj
              });
            });
          });
        });
      } else {
        docObj.updateStatus(status, (err, result) => {
          if (err) {
            return res.status(500).json({
              success: false,
              message: '更新入库单据状态失败',
              error: err.message
            });
          }
          
          res.json({
            success: true,
            message: '入库单据状态更新成功',
            data: docObj
          });
        });
      }
    });
  }

  // 取消入库单据
  static cancelInboundDocument(req, res) {
    const { id } = req.params;
    const { reason } = req.body;
    
    InboundDocument.findById(id, (err, document) => {
      if (err) {
        return res.status(500).json({
          success: false,
          message: '查询入库单据失败',
          error: err.message
        });
      }
      
      if (!document) {
        return res.status(404).json({
          success: false,
          message: '入库单据未找到'
        });
      }
      
      // 创建入库单据对象
      const docObj = new InboundDocument(
        document.id,
        document.goods_id,
        document.supplier,
        document.quantity,
        document.expected_arrival_date,
        document.actual_arrival_date,
        document.status,
        document.operator,
        document.notes,
        document.created_at
      );
      
      docObj.cancel(reason || '无原因', (err, result) => {
        if (err) {
          return res.status(500).json({
            success: false,
            message: '取消入库单据失败',
            error: err.message
          });
        }
        
        res.json({
          success: true,
          message: '入库单据已取消',
          data: docObj
        });
      });
    });
  }
}

module.exports = InboundController;